<template>
  <div class="app-page">
    <aside-tree
      title="充装检查项配置"
      :tree-data="treeData"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange"
      @refresh="getTreeData"
      @upDataTree="upDataTree"
    />
    <div class="content">
      <div style="margin-bottom: 0.266667rem;" class="btn-group">
        <div>
          <el-button
            v-permission="1"
            type="primary"
            icon="el-icon-search"
            @click="onSearch"
          >查询</el-button>
          <el-button
            v-permission="2"
            type="primary"
            icon="el-icon-plus"
            @click="add"
          >新增</el-button>
          <el-button
            v-permission="4"
            type="primary"
            icon="el-icon-delete"
            @click="dels"
          >删除</el-button>
          <el-button
            v-if="settingInfo && settingInfo.checked"
            type="primary"
            @click="qualified"
          >合格判定</el-button>
          <el-button v-permission="7" type="primary" @click="history">变更历史</el-button>
          <el-button
            v-if="itemId === 0"
            v-permission="9"
            type="primary"
            @click="inspection"
          >检查设置</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        :row-class-name="tableRowClassName"
        :pagination="false"
        custom-column
        :immediate-fetch="false"
        default-open
        @fetch="fetchData"
        @row-click="handleCurrentChange"
        @select="handleSelectionChange"
      />
    </div>
    <AddOrEditDailog ref="AddOrEditDailogRef" @refresh="onSearch" />
    <HistoryListDialog ref="HistoryListDialogRef" />
    <CheckSetDialog ref="CheckSetDialogRef" :setting-info="settingInfo" @refresh="checkSetRefresh" />
    <QualifiedSetDialog ref="QualifiedSetDialogRef" @refresh="onSearch" />
  </div>
</template>

<script>
  import {
    fillingcheckTypeList,
    fillingcheckList,
    fillingcheckDel,
    fillingcheckMove,
    fillingcheckCheckFrame
  } from '@/api'
  import AsideTree from './components/ConfigTree'
  import AddOrEditDailog from './components/AddOrEditDailog'
  import HistoryListDialog from './components/HistoryListDialog'
  import CheckSetDialog from './components/CheckSetDialog'
  import QualifiedSetDialog from './components/QualifiedSetDialog'
  export default {
    name: 'fillChecksConfig',
    components: {
      AsideTree,
      AddOrEditDailog,
      HistoryListDialog,
      CheckSetDialog,
      QualifiedSetDialog
    },
    data() {
      return {
        treeData: [],
        itemId: '',
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              type: 'selection'
            },
            {
              label: '检查类别',
              prop: 'itemType',
              width: 150,
              render: (h, { row }) => {
                return (
                <span>
                  {row.itemType === 1 ? '充装前检查' : row.itemType === 2 && '充装后检查'}
                </span>
                )
              }
            },
            {
              label: '检查类型',
              prop: 'itemName',
              width: 150
            },
            { label: '检查项', prop: 'itemDetailName' },
            {
              label: '合格判定',
              prop: 'check',
              width: 150,
              align: 'center',
              render: (h, { row }) => {
                return (
                <span>
                  {row.check === 1 ? '勾选合格' : row.check === 0 && '不勾选合格'}
                </span>
                )
              }
            },
            {
              label: '操作',
              width: 120,
              align: 'center',
              fixed: 'right',
              render: (h, { row }) => {
                return (
                <div>
                  <el-link
                    v-permission='3'
                    underline={false}
                    size='mini'
                    onClick={() => this.edit(row)}
                  >
                    编辑
                  </el-link>

                  <el-link
                    v-permission='5'
                    underline={false}
                    size='mini'
                    onClick={() => this.move(row, 1)}
                  >
                    上移
                  </el-link>
                  <el-link
                    v-permission='6'
                    underline={false}
                    size='mini'
                    onClick={() => this.move(row, -1)}
                  >
                    下移
                  </el-link>
                </div>
                )
              }
            }
          ],
          data: []
        },
        multipleSelection: [],
        itemType: null,
        settingInfo: null
      }
    },
    created() {
      this.getTreeData()
      this.getFrameData()
    },
    methods: {
      async getFrameData() {
        const { status, data } = await fillingcheckCheckFrame()
        if (status === 200) {
          this.settingInfo = data
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleCurrentChange(val) {
        this.computedCells(val)
      },
      computedCells(val) {
        const array = this.multipleSelection
        const isBo = array.some((item, index) => {
          if (item.itemDetailId === val.itemDetailId) {
            this.$delete(array, index)
            return true
          } else {
            return false
          }
        })
        if (isBo) {
          console.log('刪除')
        } else {
          array.push(val)
        }
        console.log(this.multipleSelection)
        this.toggleSelection()
      },
      toggleSelection() {
        const rows = this.multipleSelection
        if (rows) {
          this.$refs.lbTable.clearSelection()
          rows.forEach(row => {
            this.$refs.lbTable.toggleRowSelection(row, true)
          })
        } else {
          this.$refs.lbTable.clearSelection()
        }
      },
      tableRowClassName({ row, rowIndex }) {
        const array = this.multipleSelection
        const isHave = array.some(item => {
          return item.itemId === row.itemId
        })
        if (isHave) {
          return 'warning-row'
        }
        return ''
      },
      // 查询
      async onSearch() {
        const params = {}
        if (this.itemId === 1 || this.itemId === 2) {
          params.itemType = this.itemType
        } else {
          params.itemId = this.itemId
        }
        this.fetchData(params)
      },
      currentChange(current) {
        this.itemId = current.itemId
        this.itemType = current.itemType
        const params = {}
        if (this.itemId === 1 || this.itemId === 2) {
          params.itemType = current.itemType
        } else {
          params.itemId = this.itemId
        }
        this.fetchData(params)
      },
      // 新增
      async add() {
        const data = {
          itemType: this.itemType,
          itemId: this.itemId
        }
        await this.$refs.AddOrEditDailogRef.show(1, this.itemType && data)
        this.$refs.lbTable.fetch()
      },
      // 编辑
      async edit(val) {
        await this.$refs.AddOrEditDailogRef.show(2, val)
        this.$refs.lbTable.fetch()
      },
      // 删除
      dels() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择检查项!'
          })
          return
        }
        const me = this
        const ids = this.multipleSelection.map((v) => {
          return v.itemDetailId
        })
        me.$confirm(`确认删除${this.multipleSelection.length}个检查项吗？`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await fillingcheckDel({ itemDetailIds: ids.join() })
          if (res.status === 200) {
            me.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.onSearch()
          }
        })
      },
      // 1上移  -1下移
      async move(val, type) {
        const res = await fillingcheckMove({
          itemDetailId: val.itemDetailId,
          direction: type
        })
        if (res.status === 200) {
          this.onSearch()
        }
      },
      async fetchData(parmas) {
        const res = await fillingcheckList(parmas)
        this.tableData.data = res.data
      },
      // 获取安检项配置
      async getTreeData() {
        const { status, data } = await fillingcheckTypeList({})
        if (status === 200) {
          const beforeData = []
          const afterData = []
          data.forEach((v) => {
            v.label = v.itemName
            if (v.itemType === 1) beforeData.push(v)
            else afterData.push(v)
          })
          const treeData = [
            {
              itemId: 0,
              label: '检查类别',
              itemType: 0,
              children: [
                { itemId: 1, label: '充装前检查项', children: beforeData, itemType: 1 },
                { itemId: 2, label: '充装后检查项', children: afterData, itemType: 2 }
              ]
            }
          ]
          this.treeData = treeData
        }
      // const data = res.data.map((item) => ({
      //   label: item.itemName,
      //   ...item,
      // }));
      },
      upDataTree() {
        this.getTreeData()
      },

      history() {
        this.$refs['HistoryListDialogRef'].show()
      },
      qualified() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择检查项!'
          })
          return
        }
        const ids = this.multipleSelection.map((v) => {
          return v.itemDetailId
        })
        this.$refs['QualifiedSetDialogRef'].show(ids)
      },
      inspection() {
        this.$refs['CheckSetDialogRef'].show()
      },
      checkSetRefresh() {
        this.onSearch()
        this.getFrameData()
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  padding: 0;
  .content {
    flex: 1;
    width: 0;
    padding: 0 0.266667rem 0 0.266667rem;
  }
}
// /deep/.el-table .warning-row {
//   background: red !important;
// }
</style>
